package iso8583

import "fmt"

//BitMap 位图
type BitMap struct {
	Bits    []int  //位图结构集
	BitData []byte //位图原始数据
	Second  bool   //是否有第二位图
	BitSize int
}

//BitSet 位图存储
//type BitSet []uint

//NewBitMap 创建位图
func NewBitMap() *BitMap {
	return new(BitMap)
}

//Do 处理数据
func (b *BitMap) Do(bitData []byte, p *Position) {
	bitData0 := bitData[p.Get()]
	if bitData0&0x80 == 0x80 {
		b.Second = true
		b.BitSize = 16
	} else {
		b.Second = false
		b.BitSize = 8
	}
	data := make([]byte, b.BitSize)
	copy(data, bitData[p.Get():p.Get()+b.BitSize])
	p.Add(b.BitSize)
	b.setBitMap(data)

}

//SetBitMap 设置位图
func (b *BitMap) setBitMap(bitData []byte) {
	if len(bitData) != 8 && len(bitData) != 16 {
		fmt.Println(len(bitData))
		panic("位图数据出错")
	}
	b.BitData = bitData
	b.Bits = make([]int, 0)

	for i := 0; i < b.BitSize*8; i++ {
		if b.IsExit(uint(i)) {
			b.Bits = append(b.Bits, i+1)
		}
	}
	fmt.Printf("解析bitmap:%+v", b)
}

//IsExit 判断是否存在位图
func (b *BitMap) IsExit(num uint) bool {
	index := num >> 3
	pos := num & 0x07
	return b.BitData[index]&((0x80)>>pos) != 0
}
